//
//  LRXFixPayAcountView.m
//  路人侠
//
//  Created by zhangxulong on 5/27/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXFixPayAcountView.h"
#import "LRXPocketLoadData.h"

@interface LRXFixPayAcountView()<UITextFieldDelegate>
@property (nonatomic,weak) UIButton * getVerifyBtn;
@property (nonatomic,assign) NSInteger  timer;
@property (nonatomic,weak) CADisplayLink * link;
@property (nonatomic,weak) UITextField * accountField;
@property (nonatomic,weak) UITextField * pocketPassedField;
@property (nonatomic,weak) UITextField * verifyAuthText;
@property (nonatomic,strong) NSMutableArray * textFields;
@end


@implementation LRXFixPayAcountView

- (instancetype)init{
    self = [super init];
    self.backgroundColor = [UIColor whiteColor];
    CGFloat viewX = 42 * wScale;
    CGFloat viewW = MainScreenW - 2 * viewX;
    CGFloat viewY = 288 * hScale;
    CGFloat viewH = 600 * hScale;
    self.frame = CGRectMake(viewX, viewY, viewW, viewH);
    self.timer = 60;
    
    self.textFields = [NSMutableArray array];
    
    UILabel * headlabel = [[UILabel alloc]init];
    headlabel.text = @"修改绑定支付宝账号";
    headlabel.font = [UIFont systemFontOfSize:28 * hScale];
    headlabel.frame = CGRectMake(36 * wScale, 30 * hScale, 0, 0);
    [headlabel sizeToFit];
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(headlabel.frame) + headlabel.frame.origin.y, self.frame.size.width, 2 * hScale)];
    lineView.backgroundColor = mainColor;
    
    UITextField * accountField = [[UITextField alloc]initWithFrame:CGRectMake(65 * wScale, CGRectGetMaxY(lineView.frame) + 75 * hScale, self.frame.size.width - 65 * 2 * wScale, 30 * hScale)];
    accountField.placeholder = @"请输入新的支付宝账号";
    accountField.font = [UIFont systemFontOfSize:28 * hScale];
    accountField.tag = 0;
    UIView * accountLine = [[UIView alloc]initWithFrame:CGRectMake(60 * wScale, CGRectGetMaxY(accountField.frame) + 10 * hScale, self.frame.size.width - 120 * wScale, 2 * hScale)];
    accountLine.backgroundColor = GraylineColor;
    accountField.returnKeyType = UIReturnKeyNext;
    accountField.delegate = self;
    self.accountField = accountField;
    
    UIImageView * remindView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"waring"]];
    remindView.frame = CGRectMake(60 * wScale, CGRectGetMaxY(accountLine.frame) + 20 * hScale, 25 * hScale, 25 * hScale);
    
    NSString * remindStr = @"请输入正确的支付宝账号，否则无法提现到你的支付宝账号";
    CGFloat sizeW = accountLine.frame.size.width - remindView.frame.size.width;
    CGSize  remindSize = [remindStr boundingRectWithSize:CGSizeMake(sizeW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:24 * hScale]} context:nil].size;
    
    UILabel * remindLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(remindView.frame) + 10 * wScale, remindView.frame.origin.y - 5 * hScale, sizeW, remindSize.height)];
    remindLabel.text = remindStr;
    remindLabel.font = [UIFont systemFontOfSize:24 * hScale];
    remindLabel.textColor = orangeColor;
    remindLabel.numberOfLines = 0;
    
    UITextField * passwdText = [[UITextField alloc]initWithFrame:CGRectMake(65 * wScale, CGRectGetMaxY(remindLabel.frame) + 58 * hScale, self.frame.size.width - 65 * 2 * wScale, 30 * hScale)];
    passwdText.placeholder = @"请输入钱包密码";
    passwdText.font = accountField.font;
    passwdText.tag = 1;
    passwdText.secureTextEntry = YES;
    passwdText.returnKeyType = UIReturnKeyNext;
    passwdText.delegate = self;
    self.pocketPassedField = passwdText;
    UIView * lineView2 = [[UIView alloc]initWithFrame:CGRectMake(60 * wScale, CGRectGetMaxY(passwdText.frame) + 10 * hScale,self.frame.size.width - 120 * wScale, 2 * hScale)];
    lineView2.backgroundColor = GraylineColor;
    
    
    UITextField * verifyAuthText = [[UITextField alloc]initWithFrame:CGRectMake(65 * wScale, CGRectGetMaxY(lineView2.frame) + 30 * hScale, self.frame.size.width - 65 * 2 * wScale - 100 * wScale, 30 * hScale)];
    verifyAuthText.placeholder = @"输入验证码";
    verifyAuthText.font = accountField.font;
    verifyAuthText.tag = 2;
    self.verifyAuthText = verifyAuthText;
    verifyAuthText.delegate = self;
    UIView * lineView3 = [[UIView alloc]initWithFrame:CGRectMake(60 * wScale, CGRectGetMaxY(verifyAuthText.frame) + 10 * hScale,self.frame.size.width - 120 * wScale, 2 * hScale)];
    lineView3.backgroundColor = GraylineColor;
    
    UIButton * getVerifyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    getVerifyBtn.frame = CGRectMake(CGRectGetMaxX(lineView3.frame) - 105 * wScale, CGRectGetMaxY(lineView3.frame) - 50 * hScale, 100 *wScale, 45 * hScale);
    getVerifyBtn.backgroundColor = mainColor;
    [getVerifyBtn setTitle:@"获取" forState:UIControlStateNormal];
    [getVerifyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    getVerifyBtn.titleLabel.font = [UIFont systemFontOfSize:28 * hScale];
    getVerifyBtn.layer.cornerRadius = 5 * hScale;
    [getVerifyBtn addTarget:self action:@selector(getVerifyCode) forControlEvents:UIControlEventTouchUpInside];
    self.getVerifyBtn = getVerifyBtn;
    
    
    UIButton * accpetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [accpetBtn setTitleColor:mainColor forState:UIControlStateNormal];
    accpetBtn.frame = CGRectMake(CGRectGetMaxX(lineView3.frame) - 73 * wScale, CGRectGetMaxY(lineView3.frame) + 70 * hScale, 73 * wScale, 32 * hScale);
    accpetBtn.titleLabel.font = [UIFont systemFontOfSize: 34 * hScale];
    [accpetBtn setTitle:@"绑定" forState:UIControlStateNormal];
    [accpetBtn addTarget:self action:@selector(accpetBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.textFields addObject:accountField];
    [self.textFields addObject:passwdText];
    [self.textFields addObject:verifyAuthText];
    
    [self addSubview:accpetBtn];
    [self addSubview:getVerifyBtn];
    [self addSubview:passwdText];
    [self addSubview:verifyAuthText];
    [self addSubview:lineView2];
    [self addSubview:lineView3];
    [self addSubview:accountField];
    [self addSubview:accountLine];
    [self addSubview:remindView];
    [self addSubview:remindLabel];
    [self addSubview:headlabel];
    [self addSubview:lineView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willHide) name:UIKeyboardWillHideNotification object:nil];
    
    return self;
}
- (void)accpetBtnClick
{
    pocketLoadDataBlock loadDataBlock = ^(NSDictionary * parmDic){
        NSInteger statusCode = [parmDic[@"data"][@"status_code"] integerValue];
        if (statusCode == 1) {
            [MBProgressHUD showSuccess:@"修改成功"];
        }
        else if(statusCode == 2){
            [MBProgressHUD showError:@"请重新登录"];
        }
        else if(statusCode == 4){
             [MBProgressHUD showError:@"钱包密码错误"];
        }
        else if(statusCode == 3){
             [MBProgressHUD showError:@"验证码错误"];
        }
        else if(statusCode == 5){
            [MBProgressHUD showError:@"请设置您的钱包"];
        }
        else{
            [MBProgressHUD showError:@"参数错误"];
        }
    };
    NSDictionary * parms = @{@"newAccount":self.accountField.text,@"pass":self.pocketPassedField.text,@"authCode":self.verifyAuthText.text};
    LRXPocketLoadData * loadData = [[LRXPocketLoadData alloc]initWithLoadDataBlock:loadDataBlock];
    [loadData sessionDataTask:parms withUrl:changeAcount withMethod:@"POST"];
}
- (void)getVerifyCode
{
    pocketLoadDataBlock loadDataBlock = ^(NSDictionary * parmDic){
        NSInteger statusCode = [parmDic[@"data"][@"status_code"] integerValue];
        if (statusCode == 1) {
            [self addDisplayLink];
        }
        else if(statusCode == 2){
            [MBProgressHUD showError:@"请重新登录"];
        }
    };
    LRXPocketLoadData * loadData = [[LRXPocketLoadData alloc]initWithLoadDataBlock:loadDataBlock];
    NSDictionary * paramDic = @{@"type":@"3"};
    [loadData sessionDataTask:paramDic withUrl:validateUrl withMethod:@"GET"];
    
}
#pragma mark - 定时器的设置
- (void)addDisplayLink
{
    //创建一个CADisplayLink定时器
    CADisplayLink * link = [CADisplayLink displayLinkWithTarget:self selector:@selector(changeBtnText)];
    // 标识间隔多少帧调用一次selector 方法
    link.frameInterval = 60;
    //加入主循环中
    [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    self.link = link;
}

- (void)removeDisplayLink
{
    [self.link removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)changeBtnText
{
    self.timer -= 1;
    [self.getVerifyBtn setTitle:[NSString stringWithFormat:@"%ld",self.timer] forState:UIControlStateNormal];
    
    // 移除定时器 可以重新添加新的定时器了
    if (self.timer <= 0) {
        self.getVerifyBtn.enabled = YES;
        [self.getVerifyBtn setTitle:@"获取" forState:UIControlStateNormal];
        self.timer = 60;
        [self removeDisplayLink];
    }
}
#pragma mark - 键盘配合textField的view
-(void)willShow:(NSNotification *)notifi{

    UITextField *currentTf = self.textFields[[self indexOfFirstResponder]];
    CGFloat maxY = CGRectGetMaxY(currentTf.frame) + self.frame.origin.y;
    
    
    //2.获取键盘的y值
    CGRect kbEndFrm = [notifi.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat kbY = kbEndFrm.origin.y;
    
    //3.进行比较
    //计算距离
    CGFloat delta = kbY - maxY - 70 * hScale;
    //需要往上移
    if(delta < 0){
        //添加个动画
        [UIView animateWithDuration:0.25 animations:^{
            self.transform = CGAffineTransformMakeTranslation(0, delta);
        }];
        
    }
}

/**
 *  隐藏键盘
 */
-(void)willHide{
    [UIView animateWithDuration:0.25 animations:^{
        self.transform = CGAffineTransformIdentity;
    }];
}

/**
 *  获取当前的响应者的索引
 */
-(NSInteger)indexOfFirstResponder{
    
    //isFirstResponder 判断对象是否时第一响应者
    
    for (UITextField * tf in self.textFields) {
        if (tf.isFirstResponder) {
            return tf.tag;
        }
    }
    //返回一1没有当前响应者
    return -1;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //键盘退出
    [self endEditing:YES];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self removeDisplayLink];
}


#pragma mark - UITextField 的代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    if (textField.tag == 0) {
        UITextField * pp  = [self viewWithTag:1];
        [pp becomeFirstResponder];
    }
    else if(textField.tag == 1){
        UITextField * pp = [self viewWithTag:2];
        [pp becomeFirstResponder];
    }
    else if(textField.tag == 2)
    {
        [self endEditing:YES];
    }
    return YES;
}
@end
